﻿/******************************************************
* author :  cwj
* email  :  chenwenji_360@live.com 
* history:  created by cwj 2015/7/16 16:25:58 
* clrversion :4.0.30319.18444
******************************************************/

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Machine.DataAccess.Linq
{
    class TranslateResult
    {
        public TranslateResult(string sqlText, dynamic parameters)
        {
            this.SqlText = sqlText;
            this.Parameters = parameters;
        }

        public string SqlText { get; private set; }
        public dynamic Parameters { get; private set; }

        public IEnumerable<DbParameter> GetParameters(DbCommand command)
        {
            List<DbParameter> list = new List<DbParameter>();
            if (this.Parameters == null) return list;
            if (this.Parameters.GetType().Name.StartsWith("<>"))
            {
                var property = this.Parameters.GetType().GetProperties();
                foreach (var item in property)
                {
                    var c = command.CreateParameter();
                    c.ParameterName = item.Name;
                    c.Value = item.GetValue(this.Parameters, null);
                    list.Add(c);
                }
                return list;
            }
            if ((this.Parameters as IDictionary<string, object>) != null)
            {
                var dic = Parameters as IDictionary<string, object>;
                foreach (var item in dic)
                {
                    var c = command.CreateParameter();
                    c.ParameterName = item.Key;
                    c.Value = item.Value;
                    list.Add(c);
                }
                return list;
            }
            if(this.Parameters is IEnumerable<DbParameter>)
            {
                list.AddRange(this.Parameters);
            }
            return list;
        }
    }
}
